#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/27 21:40
# @Author  : leon yan
# @Site    :
# @File    : UserLogin.py
# @Software: PyCharm
import json

from PyQt5.QtCore import pyqtSlot, pyqtSignal
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox

import Globalist as gl
from lib.qsqledit import QSQL
from resource.UserLogin_ui import Ui_Form


class QUserLogin(QWidget, Ui_Form):
    LoginIsOk = pyqtSignal()
    LoginIsNg = pyqtSignal()

    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        self.UserDb = {}
        self._readUser()
        self.psw_le.returnPressed.connect(self.on_btnApply_clicked)
        # # 临时
        # self.account_le.setText("Admin")
        # self.psw_le.setText('111111')

    def __del__(self):
        print("UserLogin is deleted")

    def closeEvent(self, event):
        if gl.global_var["userVar"]["LoginUser"] == '':
            self.LoginIsNg.emit()

    @pyqtSlot()
    def on_btnClose_clicked(self):
        self.LoginIsNg.emit()
        self.close()

    def _readUser(self):
        aFields = ['id', 'UserName', 'LoginId', 'Password', 'Phone', 'LevelType', 'Descriptions', 'Admin']
        obj = QSQL("UserTable", "", " order by id desc", aFields)
        rdData = obj.showLst()
        retDataLst = json.loads(rdData)
        for i in range(len(retDataLst)):
            self.UserDb[retDataLst[i][2]] = [retDataLst[i][1], retDataLst[i][3], retDataLst[i][7]]

    @pyqtSlot()
    def on_btnApply_clicked(self):
        # 定义登录模块
        uName = self.account_le.text().strip()
        uPass = self.psw_le.text().strip()
        if uName and uName in self.UserDb:
            if self.UserDb[uName][1] == uPass:  # 判断用户名与密码是否对应
                gl.global_var["userVar"]["LoginUser"] = str(uName)
                gl.global_var["userVar"]["LoginUserName"] = self.UserDb[uName][0]
                gl.global_var["userVar"]["LoginStatus"] = self.UserDb[uName][0]
                if self.UserDb[uName][2]:
                    gl.global_var["userVar"]["Admin"] = 1
                else:
                    gl.global_var["userVar"]["Admin"] = 0
                self._loginOK()
            else:
                QMessageBox.warning(self, "警告", "登入失败")
        else:
            QMessageBox.warning(self, "警告", "用户不存在")

    def _loginOK(self):
        QMessageBox.information(self, "提示", '登入成功')
        self.LoginIsOk.emit()
        self.close()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    objWindow = QUserLogin()

    objWindow.show()
    sys.exit(app.exec_())
